package org.jfk.tbox.model;

import java.util.List;

import org.apache.log4j.Logger;
import org.jfk.core.model.SqlFilter;
import org.jfk.sys.dictionary.Dict;
import org.jfk.sys.user.User;
import org.jfk.tbox.controller.TboxMsgLogController;

import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.DbKit;
import com.jfinal.plugin.activerecord.Model;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Table;
import com.jfinal.plugin.activerecord.TableMapping;

public class TboxMsgLog extends Model<TboxMsgLog> {
	private static Logger logger = Logger.getLogger(TboxMsgLog.class);	
	public static final TboxMsgLog dao;
	public static final Table table;
	public static final String tableName;
	static {
		dao = new TboxMsgLog();
		table = TableMapping.me().getTable(TboxMsgLog.class);
		tableName = table.getName();
	}

	
	/**
	 * 返回默认列表
	 * @param controller
	 * @return
	 */
	public Page<TboxMsgLog> paginate(TboxMsgLogController controller){
		String select = " select "+tableName+".*,ot1.loginName creator_loginName,ot2.dict_value disposeStatusName,ot4.dict_value alertType_cnName,ot3.vPlate,ot3.vUser";
		String from =" from "+tableName;
		String join = " left outer join "+User.tableName+" ot1 on ot1.id="+tableName+".creator"
				+ " left outer join "+Dict.tableName+" ot2 on ot2.id="+tableName+".disposeStatus"
				+ " left outer join "+Dict.tableName+" ot4 on ot4.id="+tableName+".alertType"
				+ " left outer join "+TboxDevice.tableName+" ot3 on ot3.sn="+tableName+".sn";
		String where = " where 1=1 and alertType is not null and alertType <> 0 ";
		SqlFilter filter = controller.genJsonFilter();
		
		//处理列表查询的智能搜索
		String search = controller.getPara("search");	

		if (search != null && !"".equals(search.trim())) {
			SqlFilter searchFilter = new SqlFilter();
			searchFilter.add("and", tableName+".id", "eq", search);
			searchFilter.add("or", "ot3.vPlate", "like", search);
			searchFilter.add("or", "ot3.vUser", "like", search);
			searchFilter.end();
			filter.add(searchFilter);
			controller.setAttr("search", search);
		}
		
		//加工request参数
		controller.addPageAttr();
		
		String sqlExceptSelect = from+join+where+filter.sqlText;
		sqlExceptSelect = sqlExceptSelect + controller.sqlSort;
		logger.debug(filter);
		Page<TboxMsgLog> page = dao.paginate(controller.currentPage, controller.limit, select, sqlExceptSelect, filter.params.toArray());
		return page;
	}	
	
	public int getUndisposeMsgCount(){
		List result = Db.query("select count(*) from " + tableName + " where disposeStatus = 101000 and alertType is not null and alertType <> 0");
		int total = ((Number)result.get(0)).intValue();
		return total;
	}
}
